<template>
  <div>
    <form @submit.prevent="submitForm">
      <!-- 周次复选框 -->
      <div class="form-row">
        <label>周次:</label>
        <div v-for="n in 20" :key="n" class="form-checkbox">
          <input type="checkbox" :id="'week-' + n" :value="n" v-model="selectedWeeks">
          <label :for="'week-' + n">{{ n }}</label>
        </div>
      </div>
      
      <!-- 实验室复选框 -->
      <div class="form-row">
        <label>实验室:</label>
        <div class="lab-checkbox-container">
          <div v-for="n in 22" :key="n" class="form-checkbox">
            <input type="checkbox" :id="'lab-' + (n + 900)" :value="(n + 900)" v-model="selectedLabs">
            <label :for="'lab-' + (n + 900)">{{ (n + 900) }}</label>
          </div>
        </div>
      </div>
      
      
      <!-- 表格 -->
      <table class="schedule-table">
        <thead>
          <tr>
            <th>时间/日期</th>
            <th v-for="day in days" :key="day">{{ day }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="time in times" :key="time">
            <th>{{ time }}节</th>
            <td v-for="day in days" :key="day" @click="openModal(day, time)">
            <span v-if="getAppointment(day, time)">{{ '有课' }}</span>
</td>
          </tr>
        </tbody>
      </table>
    </form>
    
    <!-- 弹窗 -->
    <div v-if="isModalVisible" class="modal">
      <div class="modal-content">
  <span class="close" @click="closeModal">&times;</span>
  <h3>所有预约信息:</h3>
  <ul>
  <li v-for="appointment in filteredAppointments" :key="appointment.id">
    课程名称: {{ appointment.courseName }}, 
    教师: {{ appointment.teacherName }}, 
    地点: {{ appointment.labName }}, 
    时间: {{ appointment.section }}节, 
    星期: {{ days[appointment.dayofweek - 1] }}, 
    周次: {{ appointment.weekRange }}
  </li>
</ul>
  <form @submit.prevent="submitAppointment">
     <!-- 实验室下拉框 -->
     <div>
            <label>实验室:</label>
            <select v-model="selectedLab">
              <option disabled value="">请选择实验室</option>
              <option v-for="lab in selectedLabs" :key="lab" :value="lab">{{ lab }}</option>
            </select>
          </div>

          
          <!-- 课程下拉框 -->
          <div>
            <label>课程名称:</label>
            <select v-model="selectedCourse">
              <option disabled value="">请选择课程</option>
              <option v-for="course in courses" :key="course.id" :value="course.id">{{ course.name }}</option>
            </select>
          </div>
          
          <!-- 提交按钮 -->
          <button type="submit">提交预约</button>
        </form>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  name: 'FreeLabsComponent',
  data() {
    return {
      selectedWeeks: [], // 选中的周次
      selectedLabs: [], // 选中的实验室
      selectedCourse: null, // 选中的课程
      courses: [], // 课程列表
      days: [1, 2, 3, 4, 5, 6, 7], // 一周的天数
      times: [1, 2, 3, 4, 5, 6], // 节次
      isModalVisible: false, // 是否显示弹窗
      selectedLab:null,
      selectedCell: null, // 选中的单元格信息
      scheduleData: [], // 后端返回的预约信息
      hoverDay: null,
      hoverTime: null,
      teacherAccount: localStorage.getItem('username'),
      filteredAppointments: [], // 存储过滤后的预约信息
      labDisabledStatus: {}, // 用于存储实验室禁用状态
    };
  },
  created() {
    this.fetchCourses();
  },
  watch: {
    selectedWeeks(newVal) {
      this.fetchScheduleData();
    },
    selectedLabs(newVal) {
      this.fetchScheduleData();
    }
  },
  methods: {
    async fetchCourses() {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('http://192.168.129.76:8080/api/courses',   {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        this.courses = response.data.data;
      } catch (error) {
        console.error('获取课程信息错误:', error);
        if (error.response && error.response.status !== 200) {
          alert('Token无效或已过期，请重新登录。');
        } else {
          alert('获取课程信息失败，请检查网络连接。');
        }
      }
    },
    async fetchScheduleData() {
      try {
        const token = localStorage.getItem('token');
        const requestData = {
          weeks: this.selectedWeeks,
          labs: this.selectedLabs
        };
        const response = await axios.post('http://192.168.129.76:8080/api/appointment_json',   requestData, {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        this.scheduleData = response.data.data; // 假设后端返回的预约信息是对象形式
      } catch (error) {
        console.error('获取预约信息错误:', error);
        if (error.response && error.response.status !== 200) {
          alert('Token无效或已过期，请重新登录。');
        } else {
          alert('发送数据失败，请检查网络连接。');
        }
      }
    },
    submitForm() {
      // 验证是否至少选择了一个周次和至少一个实验室
      if (this.selectedWeeks.length === 0) {
        alert('请选择至少一个周次。');
        return;
      }
      if (this.selectedLabs.length === 0) {
        alert('请选择至少一个实验室。');
        return;
      }
    },
    hoverCell(day, time) {
      this.hoverDay = day;
      this.hoverTime = time;
    },
    openModal(day, time) {  
  this.isModalVisible = true;  

  // 确认获取课程安排，通过选中的周和时间筛选出占用的实验室  
  const occupiedLabs = this.scheduleData  
    .filter(item => this.selectedWeeks.includes(item.week) && item.dayofweek === this.days.indexOf(day) + 1 && item.section === this.times.indexOf(time) + 1)  
    .map(item => item.labId);  

  // 设置选中的实验室编号  
  this.selectedLab = occupiedLabs.length > 0 ? occupiedLabs[0] : null;  
  const cellInfo = this.scheduleData.find(item => item.dayofweek === this.days.indexOf(day) + 1 && item.section === this.times.indexOf(time) + 1);
  this.selectedCell = cellInfo || { day: day, time: time }; // 设置默认值
  // 过滤预约信息  
  this.filteredAppointments = this.scheduleData.filter(appointment => {  
    return appointment.dayofweek === this.days.indexOf(day) + 1 &&  
           appointment.section === this.times.indexOf(time) + 1 &&  
           this.selectedWeeks.includes(appointment.week) &&  
           occupiedLabs.includes(appointment.labId);  
  });  

},
    closeModal() {
      this.selectedCell = null;
      this.isModalVisible = false; 
    },
    getAppointment(day, time) {
  return this.scheduleData.some(item =>
    item.dayofweek === this.days.indexOf(day) + 1 && item.section === this.times.indexOf(time) + 1
  );
},
filterAppointments() {
  const mergedRecords = [];
  const recordMap = new Map();

  this.scheduleData.forEach(appointment => {
    const key = `${appointment.courseName}-${appointment.teacherName}-${appointment.labName}-${appointment.section}-${appointment.dayofweek}`;
    const existingRecord = recordMap.get(key);

    if (existingRecord) {
      // 如果已存在记录，合并周次信息
      existingRecord.weeks = [...new Set([...existingRecord.weeks, appointment.week])];
    } else {
      // 否则，创建新记录，并初始化周次信息
      recordMap.set(key, { ...appointment, weeks: [appointment.week] });
    }
  });

  recordMap.forEach((value) => {
    mergedRecords.push({
      ...value,
      weekRange: value.weeks.join('-') // 将周次数组转换为字符串，例如 "1-2"
    });
  });

  this.filteredAppointments = mergedRecords;
  console.log('Filtered Appointments:', this.filteredAppointments); // 调试输出
},
async fetchScheduleData() {
  try {
    const token = localStorage.getItem('token');
    const requestData = {
      weeks: this.selectedWeeks,
      labs: this.selectedLabs
    };
    const response = await axios.post('http://192.168.129.76:8080/api/appointment_json',  requestData, {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    this.scheduleData = response.data.data; // 假设后端返回的预约信息是对象形式
    this.filterAppointments(); // 过滤预约信息
  } catch (error) {
    console.error('获取预约信息错误:', error);
    if (error.response && error.response.status !== 200) {
      alert('Token无效或已过期，请重新登录。');
    } else {
      alert('发送数据失败，请检查网络连接。');
    }
  }
},
async submitAppointment() {
  try {
    console.log('即将提交预约，selectedCell:', this.selectedCell);
    const token = localStorage.getItem('token');
    if (!this.selectedCell) {
      alert('没有选择任何课程');
      return;
    }
    const appointmentData = {
      lab: this.selectedLab,
      course: this.selectedCourse,
      weeks: this.selectedWeeks,
      dayofweek: this.selectedCell.day,
      section: this.selectedCell.time,
      teacherAccount: this.teacherAccount
    };
    // 检查实验室是否冲突
    const conflict = this.filteredAppointments.some(appointment =>
      appointment.labId === appointmentData.lab &&
      appointment.dayofweek === appointmentData.dayofweek &&
      appointment.section === appointmentData.section &&
      !this.selectedWeeks.includes(appointment.week)
    );

    if (conflict) {
      alert('预约失败，有冲突');
      return;
    }
    const response = await axios.post('http://192.168.129.76:8080/api/appointment_json/Myappointment', appointmentData, { 
    headers: { 'Authorization': `Bearer ${token}` }
    });
    if (response.status === 200) {
      alert('预约成功');
      this.closeModal();
      this.fetchScheduleData();
    } else {
      alert('预约失败');
    }
  } catch (error) {
    console.error('预约失败:', error);
    if (error.response && error.response.status !== 200) {
      alert('Token无效或已过期，请重新登录。');
    } else {
      alert('预约失败，请检查网络连接。');
    }
  }
}
  }
};
</script>

<style scoped>
.lab-checkbox-container {
  display: grid;
  grid-template-columns: repeat(11, 1fr);
  gap: 10px; /* 调整复选框之间的间距 */
}

.form-checkbox {
  margin-bottom: 10px; /* 调整最后一行复选框的底部间距 */
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px; /* 增加间距 */
  color: #1e4166; /* 设置文本颜色为蓝色 */
}

.form-checkbox {
  margin-right: 10px;
}

.form-row label {
  margin-right: 20px;
  font-weight: bold; /* 加粗标签文本 */
  color: #1a4a7d; /* 设置标签颜色为蓝色 */
}

.schedule-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px; /* 表格与表单之间的间距 */
}

.schedule-table th,
.schedule-table td {
  border: 1px solid #cfe0ff; /* 设置表格边框颜色为蓝色 */
  padding: 8px;
  text-align: center;
}

.schedule-table th {
  background-color: #d8e3f5; /* 设置表头背景颜色为蓝色 */
  color: rgb(127, 139, 192); /* 设置表头文本颜色为白色 */
}

.schedule-table td{
  background-color: #f3f7ff;
}
.schedule-table td:hover {
  background-color: #cce5ff; /* 设置鼠标悬停时的背景颜色 */
}
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;}
.close {
cursor: pointer;
float: right;
}
</style>

